<?php

namespace Modules\Admin\Http\Controllers;

use App\Admin;
use foo\bar;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Admin\Http\Requests\AddAdminUserRequest;
use Spatie\Permission\Models\Role;

class AdminUserController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
        $admins = Admin::where('name','!=','admin')->get();
        return view('admin::adminUser.index',compact('admins'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('admin::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(AddAdminUserRequest $request)
    {
        Admin::create(['name'=>$request->name,'nickname'=>$request->nickname,'password'=>bcrypt($request->password)]);
        session()->flash('success','用户添加成功');
        return back();
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('admin::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit()
    {
        return view('admin::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(AddAdminUserRequest $request,$id)
    {
        $adminuser = Admin::find($id);
        $adminuser->update(['name'=>$request->name,'nickname'=>$request->nickname,'password'=>bcrypt($request->password)]);
        session()->flash('success','用户修改成功');
        return back();
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
        Admin::destroy($id);
        return ['valid'=>1,'message'=>'删除成功'];
    }

    /**
     * 加载为用户分配角色模板
     */
    public function showRole($adminuserid){
        $admin = Admin::find($adminuserid);
        //获取当前所有角色的数据
        $roles = Role::where('name','!=',config('hd_module.webmaster'))->get();
        return view('admin::adminUser.showRole',compact('admin','roles'));

    }
    /**
     * 为用户分配角色
     */
    public function assignRole(Request $request,$adminuserid){
        $admin = Admin::find($adminuserid);
        $admin->syncRoles($request->name);
        session()->flash('success','角色设置成功');
        return back();
    }
}
